package scu.maqiang.tiangong;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

import scu.maqiang.mesh.*;
import scu.maqiang.mesh.Mesh3T4;
import scu.maqiang.numeric.MVO;

public class ReadMainEngineSurfaceData {

	public static void main(String[] args) {
		String dir = "TianGong\\MainEngine\\";
		String meshFile = dir + "MainEngine.mesh";
		Mesh3T4 mesh = new Mesh3T4().readMesh(meshFile, MeshFormat.mesh);
		System.out.println("Basic mesh information: ");
		System.out.println(mesh.getNv() + "\t" + mesh.getNt() + "\t" + mesh.getNb());
		mesh.toTecplot(dir + "MainEngineMesh.dat");
		HashSet<Integer> bdNodes = mesh.extractBoundaryNodes(0);

		int nv = mesh.getNv();
		double[] pressureData = new double[nv];
		double[] heatFluxData = new double[nv];
//		boolean[] flag = new boolean[nv];
		String dataFile = dir + "TGT100-1_a-20_wall_PH.dat";
		double[] xyz0 = new double[3];
		int count = 0;
		Scanner scanner = null;

		try {
			scanner = new Scanner(new File(dataFile));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ArrayList<double[]> data = new ArrayList<>();
		while(scanner.hasNextDouble()) {
			double xyz1 = scanner.nextDouble();
			double xyz2 = scanner.nextDouble();
			double xyz3 = scanner.nextDouble();
			double pres = scanner.nextDouble();
			double flux = scanner.nextDouble();
			data.add(new double[] {xyz1, xyz2, xyz3, pres, flux});
		}
		
		double min = 1.0e10;
		int idx = -1;
		boolean flag = false;
		for(int i = 0; i < nv; i++) {
			double[] xyz = mesh.getNode(i);
			xyz[2] = Math.abs(xyz[2]);
			min = 1.0e10;
			idx = -1;
			flag = false;
			for(int j = 0; j < data.size(); j++) {
				double[] d = data.get(j);
				d[2] = Math.abs(d[2]);
				double err0 = Math.sqrt((d[0] - xyz[0]) * (d[0] - xyz[0]) + (d[1] - xyz[1]) * (d[1] - xyz[1]) + (d[2] - xyz[2]) * (d[2] - xyz[2]));
				if (min > err0) {
					min = err0;
					idx = j;
				}
				if (err0 < 1.0e-6) {
					pressureData[i] = d[3];
					heatFluxData[i] = d[4];
					System.out.println("count: " + (++count));
					flag = true;
					break;
				}
			}
			if(!flag) {
				double[] dd = data.get(idx);
				pressureData[i] = dd[3];
				heatFluxData[i] = dd[4];
				System.out.println("count: " + (++count));
			}
		}
		System.out.println("Total Nodes:" + mesh.getNv());
		System.out.println("Surface Nodes: " + bdNodes.size());
		scanner.close();
		mesh.toTecplot(dir + "PressureData-20.dat", pressureData);
		mesh.toTecplot(dir + "heatData-20.dat", heatFluxData);
		MVO.saveArray(dir + "MainEnginePressure-20.dat", pressureData);
		MVO.saveArray(dir + "MainEngineHeatflux-20.dat", heatFluxData);

	}

}
